package tools

import (
	"bufio"
	"errors"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
	"path"
	"strings"

	"github.com/PuerkitoBio/goquery"
)

func Spider(pageUrl string) error {
	// Request the HTML page.
	// var pageUrl = "https://mmshndhsjb.hnsjb.cn/nchn5gk"

	// 解析路径
	u, err := url.Parse(pageUrl)
	if err != nil {
		return errors.New("页面路径解析失败" + pageUrl)
	}

	// 验证 host
	if u.Host != "mmshndhsjb.hnsjb.cn" {
		return errors.New("host 验证失败，非法host：" + pageUrl)
	}

	var pageBase = u.Scheme + "://" + u.Host + "/"
	// return

	res, err := http.Get(pageUrl)

	if err != nil {
		return errors.New("http.get 获取失败：" + pageUrl)
	}

	defer res.Body.Close()

	if res.StatusCode != 200 {
		return errors.New("status code error:" + res.Status)
	}

	// Load the HTML document
	doc, err := goquery.NewDocumentFromReader(res.Body)
	if err != nil {
		return errors.New("goquery 解析 html 失败:" + pageUrl)
	}

	// 增加一条记录
	var add = LastInfo{}
	add.RequestUrl = pageUrl
	add.Images = make([]string, 0)

	// Find the review items
	doc.Find("img").Each(func(i int, s *goquery.Selection) {
		// For each item found, get the band and title
		href, exist := s.Attr("src")

		if exist && strings.Contains(href, "mms_pic/") {

			if strings.Index(href, "http") == -1 {
				href = pageBase + href
			}

			// 增加图片记录
			add.Images = append(add.Images, href)

			log.Println("href:", href)
			go func() {
				if err := getImg(href); err != nil {
					log.Println("err:", err)
				}
			}()
		}
	})

	// 获取封面图
	doc.Find("#firstImgVal").Each(func(i int, s *goquery.Selection) {
		// For each item found, get the band and title
		href, exist := s.Attr("value")

		if exist && strings.Contains(href, "mms_pic/") {

			if strings.Index(href, "http") == -1 {
				href = pageBase + href
			}

			// 增加图片记录
			add.Images = append(add.Images, href)

			log.Println("href:", href)
			go func() {
				if err := getImg(href); err != nil {
					log.Println("err:", err)
				}
			}()
		}
	})

	Last_info = append(Last_info, add) // 尾部增加一个元素
	if len(Last_info) > 100 {
		Last_info = Last_info[1:] // 删除头部一个元素
	}

	return nil
}

func getImg(imgUrl string) error {
	// 示例：
	// saveBase := "./image"
	saveBase := "/home/data/projectFile/MpFront/szzrzFile/mms_pic"

	// 解析路径
	u, err := url.Parse(imgUrl)
	if err != nil {
		return errors.New("图片地址解析失败！:" + imgUrl)
	}

	fileName := path.Base(u.Path)

	path1 := path.Dir(u.Path) + "/"
	path1 = strings.Replace(path1, "/mms_pic/", "/", 1) // 删除重复路径

	savePath := saveBase + path1

	log.Println("NewFile:", savePath+fileName)

	res, err := http.Get(imgUrl)

	if err != nil {
		return errors.New("下载图片失败!：" + imgUrl)
	}

	defer res.Body.Close()

	// 获得get请求响应的reader对象
	reader := bufio.NewReaderSize(res.Body, 32*1024)

	if err := checkPath(savePath); err != nil {
		return err
	}

	file, err := os.Create(savePath + fileName)
	if err != nil {
		return errors.New("文件创建失败：" + savePath + fileName)
	}

	// 获得文件的writer对象
	writer := bufio.NewWriter(file)

	if _, err = io.Copy(writer, reader); err != nil {
		return errors.New("文件写入失败：" + savePath + fileName)
	}

	return nil
}

// check 文件夹
// 不存在则创建文件夹
func checkPath(path string) error {
	if _, err := os.Stat(path); err != nil {

		err := os.MkdirAll(path, 0755)

		if err != nil {
			return errors.New("创建文件夹失败：" + path)
		}
	}

	return nil
}
